package com.android.manghe.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import androidx.core.app.NotificationCompat;
import android.text.TextUtils;
import android.widget.RemoteViews;
import com.android.base.okhttp.okUtil.Execute;
import com.android.base.okhttp.okUtil.OKHttpUtil;
import com.android.base.okhttp.okUtil.callback.FileBack;
import com.android.base.tools.IntentController;
import com.android.base.tools.PathUtil;
import com.android.manghe.R;
import com.android.manghe.cache.StatusHolder;

import org.jetbrains.annotations.NotNull;

import java.io.File;

import static android.os.Build.VERSION_CODES.LOLLIPOP_MR1;

/**
 * Created by zhangweijun on 2016/4/27.
 */
public class DownloadService extends Service {

    private String mUrl;
    private NotificationManager mUpdateNotifyManager;
    private Notification mNotification;
    private Execute mExecute;
    private String mDir = "";//下载文件保存目录
    private boolean mIsShowNotification = true;//是否显示状态栏进度条提示

    private static DownloadService mDownloadService;
    private static ServiceConnection mServiceConnection;

    public static void start(@NotNull Context context, @NotNull String url, @NotNull String dir, boolean isShowNotification, IDownloadServiceListener listener) {
        Intent intent = new Intent(context, DownloadService.class);
        mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                mDownloadService = ((DownloadService.DownloadServiceBinder) service).getService();
                mDownloadService.
                        setSaveDir(dir).
                        isShowNotification(isShowNotification).
                        startDownload(url, listener);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                mDownloadService = null;
            }
        };
        context.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    public static void stop(Context context) {
        if (mServiceConnection != null) {
            context.unbindService(mServiceConnection);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new DownloadServiceBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    public DownloadService setSaveDir(String dir) {
        mDir = dir;
        return this;
    }

    public DownloadService isShowNotification(boolean isShowNotification) {
        mIsShowNotification = isShowNotification;
        return this;
    }

    private void initNotification() {
        mUpdateNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O && Build.VERSION.SDK_INT >= LOLLIPOP_MR1) {
            mNotification = new NotificationCompat.Builder(getApplicationContext())
                    .setTicker("App升级中...")
                    .setAutoCancel(false)
                    .build();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && Build.VERSION.SDK_INT <= LOLLIPOP_MR1) {
            mNotification = new Notification.Builder(getApplicationContext())
                    .setAutoCancel(false)
                    .setTicker("App升级中...")
                    .setWhen(System.currentTimeMillis())
                    .build();
        } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            String channelId = "UpdateChannelId";
            NotificationChannel mChannel = new NotificationChannel(channelId, "UpdateChannelName", NotificationManager.IMPORTANCE_HIGH);
            mChannel.setDescription("UpdateAppChannel");
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.GREEN);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mChannel.setShowBadge(false);
            mUpdateNotifyManager.createNotificationChannel(mChannel);

            mNotification = new NotificationCompat.Builder(getApplicationContext(), channelId)
                    .setTicker("App升级中...")
                    .setAutoCancel(false)
                    .build();

        }

        mNotification.flags |= Notification.FLAG_NO_CLEAR;
        mNotification.icon = R.mipmap.ic_launcher;
        mNotification.contentView = new RemoteViews(getPackageName(), R.layout.notification_progress_content_view);
        mNotification.contentView.setImageViewResource(R.id.notification_content_view_text_icon, R.mipmap.ic_launcher);
        mNotification.contentView.setTextViewText(R.id.notification_content_view_text_title, getString(R.string.app_name));
        mNotification.contentView.setTextViewText(R.id.notification_content_view_text_title, getString(R.string.app_name));
        mNotification.contentView.setTextViewText(R.id.notification_content_view_text_progress, "0%");
        mNotification.contentView.setProgressBar(R.id.notification_content_view_progressbar, 100, 0, false);
        mNotification.contentView.setTextViewText(R.id.notification_content_view_text_content, "正在准备...");

        mUpdateNotifyManager.notify(66666, mNotification);

    }

    private int mCurrentProgress;

    public void startDownload(String url, final IDownloadServiceListener listener) {
        mUrl = url;
        mCurrentProgress= 0;
        if (!TextUtils.isEmpty(mUrl)) {
            String localFilePath = mDir + PathUtil.getHttpFileName(mUrl);
            try {
                File apkFile = new File(localFilePath);
                if (apkFile.exists()) {
                    IntentController.openApkFile(getApplicationContext(), apkFile);
                    if (null != listener)
                        listener.onSuccess();
                    return;
                }
            } catch (Exception e) {

            }
            //正在连接，正在准备下载
            if (mIsShowNotification) {
                initNotification();
            }
            if (null != listener)
                listener.onStart();
            mExecute = new OKHttpUtil(this).url(mUrl)
                    .get().execute(new FileBack(mDir) {
                        @Override
                        public void onDownloadSuccess(String fileDir) {
                            dismissNotify();
                            IntentController.openApkFile(getApplicationContext(), new File(fileDir));
                            StatusHolder.mCanUpdateApp = true;
                            if (null != listener)
                                listener.onSuccess();
                            stopSelf();
                        }

                        @Override
                        public void onDownloading(int progress) {
                            if (StatusHolder.mCanUpdateApp) {
                                if (mIsShowNotification && mCurrentProgress<progress) {
                                    mNotification.contentView.setTextViewText(R.id.notification_content_view_text_progress, progress + "%");
                                    mNotification.contentView.setProgressBar(R.id.notification_content_view_progressbar, 100, progress, false);
                                    mNotification.contentView.setTextViewText(R.id.notification_content_view_text_content, "正在更新");
                                    mUpdateNotifyManager.notify(66666, mNotification);
                                    mCurrentProgress = progress;
                                }
                                if (null != listener)
                                    listener.onLoading(progress);
                            } else {
                                dismissNotify();
                            }
                        }

                        @Override
                        public void onDownloadFailed(Exception e) {
                            dismissNotify();
                            if (null != listener)
                                listener.onFailure();
                        }
                    });
        }
    }

    public void stopDownload() {
        if (null != mExecute) {
            mExecute.cancel();
            dismissNotify();
        }
    }

    private void dismissNotify(){
        if (mIsShowNotification) {
            mUpdateNotifyManager.cancel(66666);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopDownload();
    }

    public class DownloadServiceBinder extends Binder {

        public DownloadService getService() {
            return DownloadService.this;
        }
    }

    public interface IDownloadServiceListener {
        void onFailure();

        void onStart();

        void onLoading(int progress);

        void onSuccess();
    }
}
